<template>
    <div>
        <div class="header clearfl">
             <el-input class="el-input" placeholder="姓名" v-model="seach_name" clearable></el-input>
             <el-button type="primary">查询</el-button>
             <el-button type="primary" @click="addVisible = true">添加</el-button>
             <el-button type="success" @click="tableToExcel()">导入数据到Excel表</el-button>
             <el-button type="success" @click="handleDownload()">zip压缩</el-button>
        </div>
        <el-table v-loading="loading" :data="list" border @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column type="index" :index="indexMethod"></el-table-column> <!-- 自定义索引 -->
            <el-table-column prop="id" label="Id" width="50px"></el-table-column>
            <el-table-column prop="name" label="姓名"></el-table-column>
            <el-table-column label="日期" show-overflow-tooltip>
                <template slot-scope="scope">
                    <i class="el-icon-time"></i>
                    <span style="margin-left: 10px">{{ scope.row.date }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="sex" label="性别" width="50"></el-table-column>
            <el-table-column prop="hobby" label="爱好"></el-table-column>
            <el-table-column prop="address" label="地址" width="200px" show-overflow-tooltip></el-table-column>
            <el-table-column label="开关">
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.state" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
                </template>
            </el-table-column>

            <el-table-column fixed="right" label="操作" width="180px">
                <template slot-scope="scope">
                    <el-button @click="handleClick(scope.$index, scope.row)">修改</el-button>
                    <el-button type="danger" @click="DelClick(scope.$index)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="bottom-el clearfl">
            <el-button type="danger" :disabled="disabled == false" @click="All_del()">批量删除</el-button>
            <el-pagination class="fr"  @current-change="handleCurrentChange"  background layout="total, prev, pager, next" :total="total"></el-pagination>
        </div>

        <!-- 新增 修改 -->
        <div>
            <el-dialog title="新增" :visible.sync="addVisible" >
                <el-form :model="addruleForm" :rules="addrules" ref="addruleForm" label-width="100px" class="demo-ruleForm">
                    <el-form-item label="姓名：" prop="name">
                        <el-input v-model="addruleForm.name"></el-input>
                    </el-form-item>
                    <el-form-item label="日期：" required>
                        <el-col :span="11">
                            <el-form-item prop="date">
                                <el-date-picker type="datetime" placeholder="选择日期" v-model="addruleForm.date" style="width: 100%;"></el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-form-item>
                    <el-form-item label="状态：" prop="state">
                        <el-switch v-model="addruleForm.state"></el-switch>
                    </el-form-item>
                    <el-form-item label="爱好：" prop="hobby">
                        <el-checkbox-group v-model="addruleForm.hobby">
                            <el-checkbox label="吃饭" name="hobby"></el-checkbox>
                            <el-checkbox label="喝酒" name="hobby"></el-checkbox>
                            <el-checkbox label="写代码" name="hobby"></el-checkbox>
                            <el-checkbox label="蹦迪" name="hobby"></el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                    <el-form-item label="性别：" prop="sex">
                        <el-radio-group v-model="addruleForm.sex">
                        <el-radio label="男"></el-radio>
                        <el-radio label="女"></el-radio>
                    </el-radio-group>
                    </el-form-item>
                    <el-form-item label="地址：" prop="address">
                        <el-input type="textarea" v-model="addruleForm.address"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="subm_add('addruleForm')">立即添加</el-button>
                        <el-button @click="resetForm('addruleForm')">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>

            <el-dialog title="修改" :visible.sync="updateVisible" >
                <el-form :model="updateForm" :rules="addrules" ref="updateForm" label-width="100px" class="demo-ruleForm">
                    <el-form-item label="姓名：" prop="name">
                        <el-input v-model="updateForm.name"></el-input>
                    </el-form-item>
                    <el-form-item label="日期：" required>
                        <el-col :span="11">
                            <el-form-item prop="date">
                                <el-date-picker type="datetime" placeholder="选择日期" v-model="updateForm.date" style="width: 100%;"></el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-form-item>
                    <el-form-item label="状态：" prop="state">
                        <el-switch v-model="updateForm.state"></el-switch>
                    </el-form-item>
                    <el-form-item label="爱好：" prop="hobby">
                        <el-checkbox-group v-model="updateForm.hobby">
                            <el-checkbox label="吃饭" name="hobby"></el-checkbox>
                            <el-checkbox label="喝酒" name="hobby"></el-checkbox>
                            <el-checkbox label="写代码" name="hobby"></el-checkbox>
                            <el-checkbox label="蹦迪" name="hobby"></el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                    <el-form-item label="性别：" prop="sex">
                        <el-radio-group v-model="updateForm.sex">
                        <el-radio label="男"></el-radio>
                        <el-radio label="女"></el-radio>
                    </el-radio-group>
                    </el-form-item>
                    <el-form-item label="地址" prop="address">
                        <el-input type="textarea" v-model="updateForm.address"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="subm_update('updateForm')">立即修改</el-button>
                        <el-button @click="resetForm('updateForm')">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
        </div>
    </div>
</template>

<script>
import {export_txt_to_zip} from '../assets/js/Export2Zip.js'

export default {
  name: 'tablepage',
  data(){
      return{
          disabled:false,//用于判断批量删除按钮是否可用
          check_list:[],//勾选的数组值
          up_index:'',//修改的id
          list:[], //表格数据
          loading: false,
          total:0,//总行数
          seach_name:'',//搜索姓名
          addVisible: false,//控制添加模态框的显示和隐藏
          updateVisible:false,//控制修改模态框的显示和隐藏
          addruleForm: {
                name: '',
                date: '',
                state: false,
                hobby: [],
                sex: '',
                address: ''
          },
          updateForm: {
                name: '',
                date: '',
                state: false,
                hobby: [],
                sex: '',
                address: ''
          },
          addrules: {
              name: [
                  { required: true, message: '请输入姓名', trigger: 'blur' },
                  { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
              ],
              date: [
                  { type: 'date', required: true, message: '请选择日期', trigger: 'change' }
              ],
              hobby: [
                  { type: 'array', required: true, message: '请至少选择一个爱好', trigger: 'change' }
              ],
              sex: [
                  { required: true, message: '请选择性别', trigger: 'change' }
              ],
              address: [
                  { required: true, message: '请填写你的地址', trigger: 'blur' }
              ]
          }
      }
  },
  methods:{
      //初始化表格数据
      list_data(page){
          this.loading = true;
          this.ajax_config.get('http://mock-api.com/RKDx59Ka.mock/user')
          .then((res)=>{
              this.list = res.data.list[page];
              this.total = res.data.list.length*10;
              this.loading = false;
          })
          .catch((error)=>{
              console.log(error);
          })
      },
      //修改查看
      handleClick(index, rows){
          this.updateVisible = true;
          //保存选择的索引
          this.up_index = index;

          this.updateForm.name = rows.name;
          this.updateForm.state = rows.state;
          this.updateForm.hobby = rows.hobby.split(',');
          this.updateForm.sex = rows.sex;
          this.updateForm.date =  this.str_time(rows.date);
          this.updateForm.address = rows.address;
      },
      //复选框的勾选状态
      handleSelectionChange(val){
          this.disabled = val.length != 0?true:false;
          this.check_list = val;
      },
      //批量删除
      All_del(){
          this.$confirm('确定批量删除, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
          }).then(() => {
              for(let item in this.check_list){
                for(let items in this.list){
                    if(this.check_list[item].id == this.list[items].id){
                        this.list.splice(items,1);
                    }
                }
              }
              this.$message({ type: 'success',message: '批量数据删除成功!'});
          }).catch(() => {
              this.$message({type: 'info',message: '已取消删除'});          
          });
      },
      //自定义索引
      indexMethod(index) {
        return index * 1;
      },
      //分页
      handleCurrentChange(page) {
        this.list_data(page-1);
      },
      //添加
      subm_add(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
              let str_hobby = this.addruleForm.hobby.join(',');//将数组已特定分割标准转成字符串
              let date = new Date(this.addruleForm.date);  
              let date_value = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + this.checkTime(date.getHours()) + ':' + this.checkTime(date.getMinutes()) + ':' + this.checkTime(date.getSeconds());  

              let obj = {
                  "id":41,
                  "date": date_value,
                  "name": this.addruleForm.name,
                  "sex":this.addruleForm.sex,
                  "address": this.addruleForm.address,
                  "state":this.addruleForm.state,
                  "hobby":str_hobby
              };
              //添加进数组，向头部添加
              this.list.unshift(obj);
              this.addVisible = false;
              this.$message({
                message: '添加数据成功',
                type: 'success'
              })
          } else {
            return false;
          }
        });
      },
      //修改(
      subm_update(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
              this.$confirm('确定修改此数据, 是否继续?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
              }).then(() => {
                  //标准时间格式转换成字符串格式
                  let date = new Date(this.updateForm.date);  
                  let date_value = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + this.checkTime(date.getHours()) + ':' + this.checkTime(date.getMinutes()) + ':' + this.checkTime(date.getSeconds()); 

                  this.list[this.up_index].name = this.updateForm.name;
                  this.list[this.up_index].state = this.updateForm.state;
                  this.list[this.up_index].hobby = this.updateForm.hobby;
                  this.list[this.up_index].sex = this.updateForm.sex;
                  this.list[this.up_index].date = date_value;
                  this.list[this.up_index].address = this.updateForm.address;
                  this.$message({ type: 'success',message: '修改成功!'});
              }).catch(() => {
                  this.$message({type: 'info',message: '已取消修改'});          
              })
              this.updateVisible = false;
          } else {
            return false;
          }
        })
      },
      //重置
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      //删除
      DelClick(index){
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            this.list.splice(index,1);
            this.$message({ type: 'success',message: '删除成功!'});
        }).catch(() => {
            this.$message({type: 'info',message: '已取消删除'});          
        });
      },
      //字符传转时间格式
      str_time(date) {  
        var t = Date.parse(date);  
        if (!isNaN(t)) {  
            return new Date(Date.parse(date.replace(/-/g, "/")));  
        }else{  
            return new Date();  
        }  
      },
      //时间转化
      checkTime(i){
        if (i<10){
            i="0" + i;
        }
        return i;
      },
      //导入数据到Excel表
      tableToExcel(){
        //要导出的json数据
        const jsonData = this.list;
        //列标题
        let head =
         `<tr>
             <td>ID编号</td>
             <td>姓名</td>
             <td>性别</td>
             <td>地址</td>
             <td>时间</td>
             <td>爱好</td>
             <td>状态</td>
        </tr>`;

        let tbody="";//内容
        //循环遍历，每行加入tr标签，每个单元格加td标签
        for(let item in jsonData){
            //增加\t为了不让表格显示科学计数法或者其他格式
            tbody+=`<tr>
                <td>${jsonData[item].id + '\t'}</td>
                <td>${jsonData[item].name + '\t'}</td>
                <td>${jsonData[item].sex + '\t'}</td>
                <td>${jsonData[item].address + '\t'}</td>
                <td>${jsonData[item].date + '\t'}</td>
                <td>${jsonData[item].hobby + '\t'}</td>
                <td>${jsonData[item].state + '\t'}</td>
            </tr>`
        }
        let str = head+tbody;

        //名称
        let worksheet = 'Sheet1'
        let uri = 'data:application/vnd.ms-excel;base64,';
    
        //下载的表格模板数据
        let template = `<html xmlns:o="urn:schemas-microsoft-com:office:office" 
        xmlns:x="urn:schemas-microsoft-com:office:excel" 
        xmlns="http://www.w3.org/TR/REC-html40">
        <head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
        <x:Name>${worksheet}</x:Name>
        <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
        </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
        </head><body><table>${str}</table></body></html>`;
        //下载模板
        window.location.href = uri + this.base64(template);
      },
      //输出base64编码
      base64 (s) {
          return window.btoa(unescape(encodeURIComponent(s)));
      },
      //生成压缩文件
      handleDownload() {
          let tHeader = ['ID编号', '姓名', '性别', '地址', '时间','爱好','状态'];//这里是头部
          let data = this.formatJson(this.list);
          export_txt_to_zip(tHeader, data, 'zjps', 'zjps');
      },
      //这里将对象格式改成数组格式
      formatJson(jsonData) {
          let arr = [];//添加一个数组
          //遍历循环
          for(let item in jsonData){
              //我这里是为了把顺序排行取的是对象里面的数据
              arr.push([jsonData[item].id,jsonData[item].name,jsonData[item].sex,jsonData[item].address,jsonData[item].date,jsonData[item].hobby,jsonData[item].state]);
          }
          return arr;
      }
  },
  created(){
    this.list_data(0);
  }
}
</script>

<style lang="less" scoped>
    .box{
        background: red;
    }
    .bottom-el{
        background: white;
        padding: 20px;
        margin-top: 50px;
    }
    .header{
        background: white;
        padding: 20px;
        display: flex;
    }
    .header .el-input{
        width: 200px;
        margin-right: 10px;
    }
</style>
